<script setup lang="ts">
import { ref, onMounted } from 'vue'
import NavBar from '../components/NavBar.vue'
import axios from 'axios'
import { useRoute } from 'vue-router'

// 定义消息类型
interface Message {
  role: 'assistant' | 'user'
  content: string
}

// 定义 Token 类型为 string | null
let Token: string | null = "";

const getToken = () => {
  Token = sessionStorage.getItem("phone") || ""; // 如果获取不到则赋值为空字符串
}

const initializeChat = async () => {
  try {
    const response = await apiClient.get('/dialogue/dialogue/initialize', {
      headers: {
        'Token': Token ? `${Token}` : ''
      }
    });
    console.log("初始化对话成功:", response.data);
    return response.data.data; // 假设返回的整数在 response.data 中
  } catch (error) {
    console.error("初始化对话失败:", error);
    return null; // 返回 null 以表示失败
  }
}

// 定义一个变量来存储初始化值
let initValue: number | null = null;

// 确保在组件挂载时获取 Token
onMounted(async () => {
  const route = useRoute();
  // 判断是否从其他页面跳转过来，这里假设从其他页面跳转过来时会带有from参数
  if (route.query.from) {
    showGreeting.value = true;
  }
  getToken(); // 确保在组件挂载时获取 Token
  initValue = await initializeChat(); // 调用初始化方法并接收返回值
  console.log("初始化返回值:", initValue); // 处理返回的整数值
});

// 创建 axios 实例
const apiClient = axios.create({
  baseURL: '/api',
});

// 添加请求拦截器
apiClient.interceptors.request.use(
  config => {
    if (Token) {
      config.headers['Token'] = `${Token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
apiClient.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    console.error('请求失败:', error);
    throw error;
  }
);

// 在 sendMessageToServer 中使用 Token 时进行空值检查
const sendMessageToServer = async (messages: Message[], initValue: number | null) => {
  try {
    const { data } = await apiClient.post(
      `/dialogue/dialogue/getMessage?initValue=${initValue}`,  // 将 initValue 作为查询参数
      messages.map(msg => ({  // 确保将消息格式化为后端期望的格式
        role: msg.role,
        content: msg.content
      })),  
      {
        headers: {
          'Content-Type': 'application/json',
        }
      }
    );
    return data.data;
  } catch (error) {
    console.error('发送消息失败:', error);
    throw error;
  }
}

// 发送消息前再次检查 Token
const sendMessage = async () => {
  if (!inputText.value.trim()) return

  // 创建新的用户消息
  const newMessage: Message = {
    role: 'user',
    content: inputText.value
  }

  // 添加到消息数组
  messages.value.push(newMessage)

  // 清空输入框
  const userQuestion = inputText.value
  inputText.value = ''

  // 显示思考状态
  isThinking.value = true

  try {
    // 再次检查 Token 是否可用
    if (!Token || Token === "") {
      messages.value.push({
        role: 'assistant',
        content: '请先登录以继续对话。'
      });
      throw new Error('Token is not available');
    }

    // 调用后端接口
    const response = await sendMessageToServer(messages.value, initValue); // 使用存储的 initValue

    // 添加AI响应
    if (response) {
      messages.value.push({
        role: 'assistant',
        content: response.content || `这是对"${userQuestion}"的回答...`
      })
    }
  } catch (error) {
    // 发生错误时显示错误消息
    messages.value.push({
      role: 'assistant',
      content: '抱歉，发生了一些错误，请稍后重试。'
    })
  } finally {
    isThinking.value = false
  }
}

// 建议问题列表
const suggestions = ref([
  '请为我设计一份年终总结',
  '请帮我画一幅写实的兔子的画',
  '请帮分析一下最近3天A股的走势'
])

// 聊天记录
const messages = ref<Message[]>([])

// 输入框内容
const inputText = ref('')
// 是否显示思考状态
const isThinking = ref(false)
// 是否显示问候语
const showGreeting = ref(false)  

// 点击建议问题
const handleSuggestionClick = (question: string) => {
  inputText.value = question
  sendMessage()
}

// 换一批建议
const refreshSuggestions = () => {
  // 这里可以调用API获取新的建议，现在只是简单地打乱顺序
  suggestions.value = suggestions.value.sort(() => Math.random() - 0.5)
}
</script>

<template>
  <div class="app-container">
    <NavBar />
    <div class="chat-container">

      <!-- 显示问候语 -->
      <div v-if="showGreeting" class="greeting-message">
        <h3>你好，又见面啦！</h3>
        <h3>我是你的超级AI助手~</h3>
        <p>你有什么想对我说的么？</p>
      </div>

      <!-- 渲染消息列表 -->
      <template v-for="(msg, index) in messages" :key="index">
        <div v-if="msg.role === 'assistant'" class="ai-message">
          <p>{{ msg.content }}</p>
        </div>
        <div v-else class="user-message">
          <div class="message">{{ msg.content }}</div>
        </div>
      </template>

      <!-- 建议问题 -->
      <div v-if="messages.length === 0" class="suggestions">
        <div class="suggestion-header">
          <span>你可以尝试这样问我：</span>
          <span class="refresh" @click="refreshSuggestions">
            <i class="refresh-icon"></i>
            换一批
          </span>
        </div>
        <div class="suggestion-items">
          <div v-for="(item, index) in suggestions" :key="index" class="suggestion-item"
            @click="handleSuggestionClick(item)">
            {{ item }}
          </div>
        </div>
      </div>

      <!-- 思考状态 -->
      <div v-if="isThinking" class="thinking">
        <div class="dots">
          <span></span>
          <span></span>
          <span></span>
          <span></span>
        </div>
        <span class="thinking-text">正在思考中</span>
      </div>
    </div>

    <!-- 输入栏 -->
    <div class="input-bar">
      <button class="help-button">
        <i class="help-icon"></i>
      </button>
      <button class="refresh-button">
        <i class="refresh-icon"></i>
      </button>
      <input v-model="inputText" type="text" placeholder="你可以问我任何问题~" @keyup.enter="sendMessage" />
      <button class="send-button" @click="sendMessage">
        <i class="send-icon"></i>
      </button>
    </div>
  </div>
</template>

<style scoped>
.greeting-message {
  background: #e1f5fe;
  padding: 15px;
  border-radius: 10px;
  margin-bottom: 20px;
  color: #333;
}

.app-container {
  max-width: 414px;
  margin: 0 auto;
  height: 100vh;
  background: #fff;
  position: relative;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.chat-container {
  padding: 20px;
  overflow-y: auto;
  height: calc(100vh - 140px);
  margin-top: 84px;
}

.ai-message {
  background: #f8f8f8;
  padding: 15px;
  border-radius: 10px;
  margin-bottom: 20px;
}

.ai-message p {
  margin: 5px 0;
  line-height: 1.5;
  color: #333;
}

.suggestions {
  margin: 20px 0;
}

.suggestion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  color: #666;
}

.refresh {
  color: #007AFF;
  display: flex;
  align-items: center;
  gap: 5px;
}

.suggestion-items {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.suggestion-item {
  background: #f8f8f8;
  padding: 12px 15px;
  border-radius: 8px;
  color: #333;
}

.user-message {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.user-message .message {
  background: #007AFF;
  color: white;
  padding: 12px 15px;
  border-radius: 18px;
  max-width: 80%;
}

.thinking {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 20px 0;
}

.dots {
  display: flex;
  gap: 3px;
}

.dots span {
  width: 6px;
  height: 6px;
  background: #ccc;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out;
}

.dots span:nth-child(1) {
  animation-delay: 0s;
}

.dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.dots span:nth-child(3) {
  animation-delay: 0.4s;
}

.dots span:nth-child(4) {
  animation-delay: 0.6s;
}

@keyframes bounce {

  0%,
  80%,
  100% {
    transform: scale(0.6);
  }

  40% {
    transform: scale(1);
  }
}

.thinking-text {
  color: #666;
  font-size: 14px;
}

.input-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  max-width: 414px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  padding: 10px 20px;
  background: white;
  border-top: 1px solid #eee;
  gap: 10px;
}

.input-bar button {
  width: 32px;
  height: 32px;
  border: none;
  background: none;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}

.input-bar input {
  flex: 1;
  height: 36px;
  border: none;
  background: #f8f8f8;
  border-radius: 18px;
  padding: 0 15px;
  font-size: 14px;
}

.input-bar input::placeholder {
  color: #999;
}

/* 图标样式 */
.help-icon,
.refresh-icon,
.send-icon,
.user-icon {
  width: 24px;
  height: 24px;
  background-size: contain;
  background-repeat: no-repeat;
}

.help-icon {
  background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="%23666" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"/></svg>');
}

.refresh-icon {
  background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="%23666" d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/></svg>');
}

.send-icon {
  background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="%23007AFF" d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>');
}
</style>